package com.gitee.wsl.doc.prosemirror.transform.ext

import com.gitee.wsl.doc.prosemirror.exception.RangeError
import com.gitee.wsl.doc.prosemirror.model.mark.Mark
import com.gitee.wsl.doc.prosemirror.model.mark.MarkType
import com.gitee.wsl.doc.prosemirror.transform.TransformAble
import com.gitee.wsl.doc.prosemirror.transform.step.AddNodeMarkStep
import com.gitee.wsl.doc.prosemirror.transform.step.RemoveNodeMarkStep

// Add a mark to the node at position `pos`.
fun<T: TransformAble> T.addNodeMark(pos: Int, mark: Mark) = this.apply {
    step(AddNodeMarkStep(pos, mark))
}

// Remove a mark (or a mark of the given type) from the node at
// position `pos`.
fun<T: TransformAble> T.removeNodeMark(pos: Int, mark: Mark) = this.apply {
    step(RemoveNodeMarkStep(pos, mark))
}

fun<T: TransformAble> T.removeNodeMark(pos: Int, mark: MarkType) = this.apply {
    val node = doc.nodeAt(pos) ?: throw RangeError("No node at position $pos")
    val mark = mark.isInSet(node.marks) ?: return this
    step(RemoveNodeMarkStep(pos, mark))
}